<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入角色名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="角色编码" prop="code">
        <el-input v-model="queryParams.code" placeholder="请输入角色编码" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="角色状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择角色状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_common_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button v-hasPermi="['system:role:list']" type="primary" icon="el-icon-search" size="small"
                   @click="handleQuery">搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
        <el-button type="primary" plain icon="el-icon-plus" size="small" @click="handleAdd"
                   v-hasPermi="['system:role:add']">新增
        </el-button>
        <el-button type="danger" plain icon="el-icon-delete" size="small" :disabled="multiple" @click="handleDelete"
                   v-hasPermi="['system:role:delete']">批量删除
        </el-button>
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:role:export']"
        >导出
        </el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="roleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="角色名称" prop="name" align="center"/>
      <el-table-column label="角色编码" prop="code" align="center"/>
      <el-table-column label="角色状态" prop="status" align="center">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0"
                     @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" align="center"/>
      <el-table-column label="角色备注" prop="remark" align="center"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['system:role:update']">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['system:role:delete']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <Pagination v-show="total>0" :total="total" :page.sync="queryParams.currentPage" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入角色名称"/>
        </el-form-item>
        <el-form-item prop="code">
          <span slot="label">
            <el-tooltip content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasRole('admin')`)" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
            权限字符
          </span>
          <el-input v-model="form.code" placeholder="请输入角色编码"/>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sys_common_status"
              :key="dict.value"
              :label="Number(dict.value)"
            >{{dict.label}}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event)">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event)">全选/全不选</el-checkbox>
          <el-tree class="tree-border" :data="menuOptions" :default-checked-keys="checkedMenus"
                   show-checkbox ref="menu"
                   node-key="id" empty-text="加载中，请稍候" :props="defaultProps"></el-tree>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {listRole, getRole, delRole, addRole, updateRole, roleMenuList} from "@/api/system/role";
  import {listMenu} from "@/api/system/menu"
  import Pagination from "@/components/Pagination"

  export default {
    name: "Role",
    dicts: ['sys_common_status'],
    components: {
      Pagination
    },
    data() {
      return {
        isCheck: false,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 角色表格数据
        roleList: [],
        checkedMenus: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        menuExpand: false,
        menuNodeAll: false,
        // 菜单列表
        menuOptions: [],
        // 查询参数
        queryParams: {
          currentPage: 1,
          pageSize: 10,
          name: undefined,
          code: undefined,
          status: undefined
        },
        // 表单参数
        form: {},
        defaultProps: {
          children: "children",
          label: "name"
        },
        // 表单校验
        rules: {
          name: [{
            required: true,
            message: "角色名称不能为空",
            trigger: "blur"
          }],
          code: [{
            required: true,
            message: "权限字符不能为空",
            trigger: "blur"
          }]
        }
      };
    },
    created() {
      this.getList();
    },
    methods: {
      /** 查询角色列表 */
      getList() {
        this.loading = true;
        listRole(this.queryParams).then(response => {
          this.roleList = response.data.records;
          this.total = response.data.total;
          this.loading = false;
        });
      },
      /** 查询菜单树结构 */
      getMenuTreeselect() {
        if (this.menuOptions.length === 0) {
          listMenu({status: 1}).then(response => {
            this.menuOptions = response.data;
          });
        }
      },
      // 所有菜单节点数据
      getMenuAllCheckedKeys() {
        // 目前被选中的菜单节点
        let checkedKeys = this.$refs.menu.getCheckedKeys();
        // 半选中的菜单节点
        let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
        checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
        return checkedKeys;
      },
      /** 根据角色ID查询菜单树结构 */
      getRoleMenuTreeselect(roleId) {
        roleMenuList(roleId).then(response => {
          this.checkedMenus = response.data;
        });
      },
      // 角色状态修改
      handleStatusChange(row) {
        let text = row.status ? '启用' : '禁用'
        this.$confirm('确认要"' + text + '""' + row.name + '"角色吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          updateRole(row).then(() => {
            this.getList()
            this.$message.success(text + '成功')
          }).catch(() => {
            row.status = row.status === 1 ? 0 : 1;
          })
        }).catch(() => {
          row.status = row.status === 1 ? 0 : 1;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        if (this.$refs.menu !== undefined) {
          this.$refs.menu.setCheckedKeys([]);
        }
        this.menuExpand = false
        this.menuNodeAll = false
        this.form = {
          id: undefined,
          name: undefined,
          code: undefined,
          status: 1,
          menuIds: [],
          remark: undefined
        };
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.currentPage = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.queryParams = {}
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.multiple = !selection.length
      },
      // 树权限（展开/折叠）
      handleCheckedTreeExpand(value) {
        let treeList = this.menuOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
        }
      },
      // 树权限（全选/全不选）
      handleCheckedTreeNodeAll(value) {
        this.$refs.menu.setCheckedNodes(value ? this.menuOptions : []);
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.getMenuTreeselect();
        this.open = true;
        this.title = "添加角色";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        this.getMenuTreeselect();
        this.getRoleMenuTreeselect(row.id)
        getRole(row.id).then(response => {
          this.form = response.data;
          this.title = "修改角色";
          this.open = true;
        });
      },
      /** 提交按钮 */
      submitForm: function () {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.form.menuIds = this.getMenuAllCheckedKeys();
            if (this.form.id !== undefined) {
              updateRole(this.form).then(() => {
                this.$message.success("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addRole(this.form).then(() => {
                this.$message.success("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const roleIds = row.id || this.ids;
        this.$confirm('是否确认删除角色编号为"' + roleIds + '"的数据项？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delRole(roleIds).then(() => {
            this.getList();
            this.$message.success("删除成功");
          })
        }).catch(() => {
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('system/role/export', {
          ...this.queryParams
        }, `角色表.xlsx`)
      }
    }
  };
</script>
